package com.bawei.common.mvi

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.bawei.common.base.BaseFragment
import com.bawei.common.event.CustomEvent
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Author: Jason Zhang
 * Date: 2024/12/12
 * Desc: MVI模式下的BaseFragment
 */
abstract class BaseMviFragment<T: ViewDataBinding> : BaseFragment<T>() {


    override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View? {
        var rootView = super.onCreateView(inflater, container, savedInstanceState)
        initData()
        updateUi()
        EventBus.getDefault().register(this)
        return rootView
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveEvent(event: CustomEvent){
        if (event !=null && event.target == this::class.java.simpleName){
            handEvent(event)
        }
    }

    open fun handEvent(customEvent: CustomEvent){

    }

    override fun onDestroyView() {
        EventBus.getDefault().unregister(this)
        super.onDestroyView()
    }

    private fun initData(){
        lifecycleScope.launch {
            lifecycle.repeatOnLifecycle(Lifecycle.State.CREATED){
                sendViewIntent()
            }
        }
    }

    private fun updateUi(){
        lifecycleScope.launch {
            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED){
                collectUiState()
            }
        }
    }


    open suspend fun sendViewIntent(){

    }

    open suspend fun collectUiState(){

    }


}